package com.yb;

import com.spring.BeanPostProcessor;
import com.spring.Component;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

@Component
public class YbBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println(bean);
        Enhancer enhancer = new Enhancer();  // 通过CGLIB动态代理获取代理对象的过程
        enhancer.setSuperclass(bean.getClass());     // 设置enhancer对象的父类
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            /**
             *
             * @param o cglib生成的代理对象
             * @param method 被代理对象的方法
             * @param objects     传入方法的参数
             * @param methodProxy 代理的方法
             * @return
             * @throws Throwable
             */
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                String name = o.getClass().getName();
                System.out.println("这里可以插入执行关键代码之前的逻辑"+method.getName()+"   "+methodProxy.getSuperName()+"  "+name);
                Object o1 = methodProxy.invokeSuper(o, objects);//关键代码:
                System.out.println("这里可以插入执行关键代码之后的逻辑");
                return o1;
            }
        });
        return enhancer.create();
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        return bean;
    }
}
